﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Threading;
using System.Windows.Controls;
using System.Threading.Tasks;
using mitasoft.Books.Client.Desktop.Core;

namespace mitasoft.Books.Client.Desktop.Helpers
{
    internal class TaskHelper
    {
        private static Dispatcher _uiDispatcher = null;
        private static ProgressBar _progressBar = null;

        static TaskHelper()
        {

        }

        public static void Init(Dispatcher uiDispatcher, ProgressBar progressControl)
        {
            _uiDispatcher = uiDispatcher;
            _progressBar = progressControl;
        }

        public static void RunSynced(Action start, Action stop)
        {
            Check();

            _uiDispatcher.BeginInvoke(
                (Action)(delegate()
                {
                    _progressBar.IsIndeterminate = true;
                }));

            Task.Factory
                .StartNew(() =>
                {
                    start();
                })
                .ContinueWith((t) =>
                {
                    _uiDispatcher.BeginInvoke(
                        (Action)(delegate()
                        {
                            _progressBar.IsIndeterminate = false;
                            stop();
                        }));
                });
        }

        private static void Check()
        {
            if (_uiDispatcher == null)
                throw new ArgumentNullException("uiDispatcher");

            if (_progressBar == null)
                throw new ArgumentNullException("progressBar");
        }
    }
}
